<template>
	<view class="wrap">
		<template v-if="hasLoad">
			<view class="logo">
				<image :src="topImage || '/static/imgs/login_top_loading.jpg'" mode="widthFix"></image>
			</view>
			<view class="main">
				<view class="form">
					<view class="b-row" v-if="!fromQrcode && onlyNumber !== 2">
						<view class="b-input">
							<view class="s-icon iconfont icon-card"></view>
							<input type="text" :value="form.number" @input="onInputNumber" placeholder="请输入卡号" />
						</view>
					</view>
					<view class="b-row" v-if="!onlyNumber">
						<view class="b-input">
							<view class="s-icon iconfont icon-password"></view>
							<input type="text" :value="form.password" @input="onInputPassword" placeholder="请输入卡密" />
						</view>
					</view>
					
					<view class="b-row" v-if="onlyNumber === 2">
						<view class="b-input">
							<view class="s-icon iconfont icon-phone"></view>
							<input type="text" :value="form.phone" @input="onInputPhone" placeholder="请输入手机号" />
						</view>
					</view>
					<view class="b-row" v-if="onlyNumber === 2">
						<view class="b-input">
							<view class="s-icon iconfont icon-password"></view>
							<input type="text" :value="form.captcha" @input="onInputCaptcha" placeholder="请输入验证码" />
							<view class="s-captcha" :class="{ disable: captcha.second > 0 }" @click="onPhoneCaptcha">
								<text v-if="!captcha.retry && !captcha.second">获取验证码</text>
								<text v-else-if="captcha.second > 0">重新获取 {{ captcha.second }}秒</text>
								<text v-else-if="captcha.retry">重新获取</text>
							</view>
						</view>
					</view>
					
				</view>
				<view v-if="onlyNumber !== 2" class="submit" :class="{ disable: disable.submit }" @click="onLoginByCard">立即兑换</view>
				<view v-if="onlyNumber === 2" class="submit" :class="{ disable: disable.submit }" @click="onLoginByPhoneCaptcha">登录兑换</view>
				<view class="tips">{{loginNote}}</view>
				<view class="preview" v-if="previewUrl" @click="onPreview">礼品预览Preview</view>
			</view>
		</template>
		<!-- 加载中 -->
		<load-more :loadingType="loadingType" :loadingText="loadingText" :top="300"></load-more>
		<com-tips :show="display.tips" title="兑换提示" :content="alertTips" @bindClose="onCloseTips"></com-tips>
		<!-- 在线客服 -->
		<view class="customer-service" @click="onCustomerService">
			<image src="/static/imgs/kf.png" mode="widthFix"></image>
			<text>联系客服</text>
		</view>
	</view>
</template>

<script>
	import {
		getEnterInfo,
		loginByCard,
		loginByPhoneCaptcha,
		sendPhoneCaptcha
	} from '@/service/api/card.js'
	import {
		smartLogin
	} from '@/service/request/main.js'
	import Config from '@/service/config.js'
	import mixinsCommon from '@/mixins/common.js'
	import Util from '@/common/util.js'
	export default {
		mixins: [mixinsCommon],
		data() {
			return {
				form: {
					number: '',
					password: '',
					phone: '',
					captcha: '',
				},
				disable: {
					captcha: false,
					submit: false
				},
				display: {
					tips: false
				},
				captcha: {
					retry: false,
					second: 0,
				},
				fromQrcode: false,
				hasLoad: false,
				loadingType: 1,
				loadingText: '',
				previewUrl: '',
			}
		},
		onLoad(options) {
			console.log('web onLoad', options)
			// 设置场景
			this.$store.commit('setScenario', 'card')

			// 参数处理
			let params = options
			let from = params.from
			if (params.scene) {
				let sceneParams = Util.urlDecode(decodeURIComponent(params.scene))
				params = {...params, ...sceneParams}
				from = 'qrcode'
			}
			console.log('params value => ', params)

			// #ifdef  H5
			if (Util.isWechat()) {
				if (params.auth_key) {
					this.$store.commit('setAuthKey', params.auth_key)
				}
			}
			// #endif

			// 设置礼品卡
			if (params.cid) {
				if (this.$store.getters.cardId && params.cid != this.$store.getters.cardId) {
					this.$store.commit('delCardKey')
				}
				this.$store.commit('setCardId', params.cid)
			}

			// 自动登录
			if (!params.cid || params.cid == this.$store.getters.cardId) {
				if (this.$store.getters.cardKey) {
					uni.reLaunch({
						url: '/pages/card/index'
					})
					return
				}
			}

			// 兑换码
			if (params.number) {
				this.fromQrcode = true
				this.form.number = params.number
			}

			// 获取入口信息
			uni.login().then(([err, res]) => {
				console.log('uni.login', err, res)
				const wxCode = res ? res.code : ''
				const authKey = this.$store.getters.authKey
				getEnterInfo(wxCode, authKey).then(([err, res]) => {
					console.log('getEnterInfo', err, res);
					if (!err) {
						this.$store.commit('setCardConfig', res)
						this.previewUrl = res.preview_url
						if (this.fromQrcode && res.only_number !== 2) {
							this.onLoginByCard()
						} else if (res.card_key) {
							this.$store.commit('setCardKey', res.card_key)
							this.$logic.showToast('自动登录成功').then(([err, res]) => {
								uni.reLaunch({
									url: '/pages/card/index'
								})
							})
						} else {
							// #ifdef  H5
							if (Util.isWechat() && res.mp_login) {
								if (!this.$store.getters.authKey) {
									const baseUrl = Config.baseUrl
									const redirectUrl = encodeURIComponent(window.location.href)
									window.location.href = `${baseUrl}/web/connect?url=${redirectUrl}`
								}
							}
							// #endif
						}
						if (res.tips) {
							this.display.tips = true
						}
						// #ifdef  MP-WEIXIN
						this.hasLoad = true
						// #endif
						// #ifdef  H5
						setTimeout(() => {
							this.hasLoad = true
						}, 1000)
						// #endif
						this.loadingType = -1
					} else {
						this.loadingType = 3
						this.loadingText = err.data.msg || '加载失败'
					}
				})
			})
		},
		computed: {
			topImage() {
				return this.$store.getters.cardConfig.login_top_img
			},
			loginNote() {
				return this.$store.getters.cardConfig.login_note || '注：请根据输入框提示输入内容进行礼品兑换。'
			},
			onlyNumber() {
				return this.$store.getters.cardConfig.only_number || 0
			},
			alertTips() {
				return this.$store.getters.cardConfig.tips || ''
			}
		},
		methods: {
			onShowTips() {
				this.display.tips = true
			},
			onCloseTips() {
				this.display.tips = false
			},
			onInputNumber(e) {
				// console.log('onInputName', e)
				this.form.number = e.detail.value
			},
			onInputPassword(e) {
				// console.log('onInputPassword', e)
				this.form.password = e.detail.value
			},
			onInputPhone(e) {
				// console.log('onInputPhone', e)
				this.form.phone = e.detail.value;
			},
			onInputCaptcha(e) {
				// console.log('onInputCaptcha', e)
				this.form.captcha = e.detail.value
			},
			onPhoneCaptcha() {
				if (this.disable.captcha) {
					return
				}
				console.log('card id =>', this.$store.getters.cardId)
				const cid = this.$store.getters.cardId;
				this.disable.captcha = true
				uni.login().then(([err, res]) => {
					console.log('uni.login', err, res)
					sendPhoneCaptcha(this.form.phone, cid, res ? res.code : '', true).then(([err, res]) => {
						console.log('sendPhoneCaptcha', err, res)
						if (!err) {
							uni.showToast({
								title: '发送成功'
							})
			
							// 验证码倒计时
							this.captcha.second = 60
							var interval = setInterval(() => {
								this.captcha.second--
							}, 1000)
							setTimeout(() => {
								clearInterval(interval)
								this.captcha.retry = true
								this.captcha.second = 0
								this.disable.captcha = false
							}, this.captcha.second * 1000)
						} else {
							this.disable.captcha = false
						}
					})
				})
			},
			onLoginByPhoneCaptcha() {
				if (this.disable.submit) {
					return
				}
				if (!this.form.phone) {
					return this.$logic.showToast('手机号不能为空')
				}
				if (!this.form.captcha) {
					return this.$logic.showToast('验证码不能为空')
				}
				this.disable.submit = true
				uni.login().then(([err, res]) => {
					console.log('uni.login', err, res)
					const wxCode = res ? res.code : ''
					const authKey = this.$store.getters.authKey
					const cid = this.$store.getters.cardId;
					loginByPhoneCaptcha(this.form.phone, this.form.captcha, cid, wxCode, authKey)
						.then(([err, res]) => {
							console.log('loginByPhoneCaptcha', err, res)
							this.disable.submit = false
							if (!err) {
								this.$store.commit('setCardKey', res.cardInfo.key)
								this.$logic.showToast('登录成功').then(([err, res]) => {
									uni.reLaunch({
										url: '/pages/card/index'
									})
								})
							} else {
								// 重置
								if (this.fromQrcode) {
									this.fromQrcode = false
									this.form.number = ''
									this.form.password = ''
									this.form.phone = ''
									this.form.captcha = ''
								}
							}
						})
				})
				/*
				uni.login().then(([err, res]) => {
					console.log('uni.login', err, res)
					const wxCode = res ? res.code : ''
					const authKey = this.$store.getters.authKey
					loginByPhoneCaptcha(this.form.phone, this.form.captcha, wxCode, authKey).then(([err,
						res
					]) => {
						console.log('loginByPhoneCaptcha', err, res)
						this.disable.submit = false
						if (!err) {
							this.$store.commit('setAccessToken', res.token)
							this.$store.commit('setActivityId', res.activity_id)
							this.$logic.showToast('登录成功').then(([err, res]) => {
								uni.reLaunch({
									url: this.returnPage
								})
							})
						}
					})
				})
				*/
			},
			onLoginByCard() {
				if (this.disable.submit) {
					return
				}
				if (!this.form.number) {
					return this.$logic.showToast('卡号不能为空')
				}
				if (!this.onlyNumber && !this.form.password) {
					return this.$logic.showToast('卡密不能为空')
				}
				this.disable.submit = true;
				uni.login().then(([err, res]) => {
					console.log('uni.login', err, res)
					const wxCode = res ? res.code : ''
					const authKey = this.$store.getters.authKey
					loginByCard(this.form.number, this.form.password, wxCode, authKey)
						.then(([err, res]) => {
							console.log('loginByCard', err, res)
							this.disable.submit = false
							if (!err) {
								this.$store.commit('setCardKey', res.cardInfo.key)
								this.$logic.showToast('登录成功').then(([err, res]) => {
									uni.reLaunch({
										url: '/pages/card/index'
									})
								})
							} else {
								// 重置
								if (this.fromQrcode) {
									this.fromQrcode = false
									this.form.number = ''
									this.form.password = ''
									this.form.phone = ''
									this.form.captcha = ''
								}
							}
						})
				})
			},
			onCustomerService() {
				// 打开有赞客服链接
				const serviceUrl = 'https://shop93244668.youzan.com/v3/im/index?c=wsc&v=2&o=https%3A%2F%2Fshop93244668.youzan.com%2F&kdt_id=93052500&type=default&fromSource=%7B%22kdt_id%22%3A%2293052500%22%2C%22source%22%3A%22default%22%2C%22endpoint%22%3A%22h5%22%2C%22site_id%22%3A0%7D&reft=1734428093773&spm=f.91451403#/index'
				//const serviceUrl = 'https://work.weixin.qq.com/kfid/kfce412dbdd0a94f8f3'

				// #ifdef H5
				window.location.href = serviceUrl
				// #endif
				// #ifdef MP-WEIXIN
				uni.navigateTo({
					url: '/pages/webview/index?url=' + encodeURIComponent(serviceUrl)
				})
				// #endif
			},
			onPreview() {
				// #ifdef H5
				window.location.href = this.previewUrl
				// #endif
				// #ifdef MP-WEIXIN
				uni.navigateTo({
					url: '/pages/webview/index?url=' + encodeURIComponent(this.previewUrl)
				})
				// #endif
			}
		}
	}
</script>

<style lang="scss">
	page {
		padding-bottom: env(safe-area-inset-bottom);
		background: #ffffff;
	}

	.wrap {}

	.logo {
		image {
			width: 100%;
			height: 460upx;
		}
	}

	.main {
		padding: 50upx;
	}

	.form {
		.b-row {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 30upx;
			border-bottom: 1upx solid #E5E5E5;
		}

		.b-input {
			flex: 1;
			padding: 0 20upx;
			width: 100%;
			height: 90upx;
			display: flex;
			align-items: center;

			.s-icon {
				color: #ccc;
				font-size: 40upx;
			}
			.s-captcha {
				padding: 0 30upx;
				background: #fff;
				border: 2upx #ccc solid;
				height: 64upx;
				line-height: 64upx;
				border-radius: 32upx;
				color: #808080;
				font-size: 24upx;
			
				&.disable {
					color: #999;
				}
			}

			input {
				margin-left: 30upx;
				flex: 1;
				color: #333;
				font-size: 28upx;
			}
		}
	}

	.submit {
		margin-top: 80upx;
		height: 100upx;
		line-height: 100upx;
		text-align: center;
		color: #fff;
		font-size: 32upx;
		background: #DA5650;
		border-radius: 50upx;
		letter-spacing: 10upx;

		&.f-wechat {
			background: #35C773;
		}

		&.disable {
			background: rgba($color: #DA5650, $alpha: 0.2);
		}
	}

	.tips {
		position: fixed;
		bottom: 50upx;
		left: 50%;
		transform: translateX(-50%);
		width: 80%;
		max-width: 600upx;
		color: #383838;
		font-size: 24upx;
		text-align: center;
	}

	.preview {
		position: absolute;
		right: 50upx;
		margin-top: 20upx;
		color: #383838;
		font-size: 28upx;
		text-align: right;
	}

	.customer-service {
		position: fixed;
		right: 30upx;
		bottom: 120upx;
		z-index: 99;
		text-align: center;
		
		image {
			width: 100upx;
			height: 100upx;
		}
		
		text {
			display: block;
			font-size: 24upx;
			color: #666;
			margin-top: 4upx;
		}
	}
</style>